import { useState, useEffect } from "react";
import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import Empty from "../component/empty";
import LgSearch from "@/pages/components/searchInput";
import { HttpDelete, HttpGet, HttpPut } from "@/network/servers";
import LgRefreshPage from "@/pages/components/refreshPage";
import { connect, useDispatch } from "react-redux";
import { getStorage, getBrowserController } from "@/pages/components/utils";
import Card from "../component/card";
import Utils from "@/utils/index";
import Proxy from "@/network/proxy";
import _ from "lodash";
import { SwipeAction } from "antd-mobile";
import { useTransformUrl } from "@/utils/myUtils";
import "./index.scss";

const browserController = getBrowserController();
const storage = getStorage();

var wx = require("weixin-js-sdk");

function App(props) {
  const { userInfo, lg_ic } = props;

  const dispatch = useDispatch();
  const [sysMesList, setSysMesList] = useState<any>([]);
  const [total, setTotal] = useState(0);
  const [isOpened, setIsOpened] = useState(false);
  const [pullCount, setPullCount] = useState(1);
  const [totalPage, setTotalPage] = useState(0);
  const [currentIndex, setCurrentIndex] = useState(1);
  const [isLongPress, setIsLongPress] = useState(false);
  const [pressId, setPressId] = useState("");
  const [loadVisible, setLoadVisible] = useState(true);

  const [keyword, setKeyword] = useState("");
  const [isSearch, setIsSearch] = useState(false);

  const getToken = () => {
    if (Utils.getQueryVariable("env") === "weapp") {
      return Utils.getQueryVariable("lg_tk");
    } else {
      return storage.get("token") || Utils.getQueryVariable("lg_tk");
    }
  };

  // 搜索变化
  const searchHandle = _.debounce(
    (value) => {
      setKeyword(value.trim());
    },
    500,
    { trailing: true }
  );

  const clearAll = () => {
    Taro.showModal({
      title: "提示",
      content: "是否清除所有系统消息",
      confirmColor: "#0076ff",
      success: function (res) {
        if (res.confirm) {
          clearAllMes();
        } else if (res.cancel) {
          console.log("cancel");
        }
      },
    });
  };

  const jumpWeapp = (appId, path) => {
    try {
      browserController.navigateToMiniProgramForWebview(wx, {
        appId, //必传 跳转小程序唯一标识
        path, //必传 跳转后初始页面路径
        extraData: {},
        envVersion: "release", //必传 跳转小程序的版本
      });
    } catch (err) {
      Taro.showToast({ title: err, icon: "none" });
    }
  };

  const computeSwipe = (item) => {
    //计算滑块的操作项
    if (item.isClosable == 1) {
      return [
        {
          key: "shield",
          text: "屏蔽此类消息",
          color: "#009cff",
          onClick: () => shieldMessage(item),
        },
        {
          key: "del",
          text: "删除",
          color: "#e75d58",
          fontSize: "15px",
          onClick: () => delMessage(item),
        },
      ];
    } else {
      return [
        {
          key: "del",
          text: "删除",
          color: "#e75d58",
          onClick: () => delMessage(item),
        },
      ];
    }
  };

  // 点击事件
  const toLink = (item) => {
    const { SchoolID, UserID } = userInfo;

    if (item.status == 0) {
      HttpPut({
        url: "/api/system/manage/update/status",
        data: {
          userId: UserID,
          schoolId: SchoolID,
          sysMsgId: item.sysMsgId,
        },
      }).then(() => {
        getSysMes();
        setTimeout(() => {
          window.getNewRemindCount &&
            typeof window.getNewRemindCount === "function" &&
            window.getNewRemindCount();
        }, 1000);
      });
    }

    if (Utils.getSystemInfo() === "h5") {
      if (item.pcLinkType == 1 && item.appLink) {
        if (item.sysId == 220) {
          //通知公告
          let url =
            window.baseUrl +
            item.appLink
              .replace("[token]", getToken())
              .replace(
                "[IdentityCode]",
                storage.get("lg_ic") || Utils.getQueryVariable("lg_ic")
              );
          window.open(url, "_self");
        } else {
          HttpGet({
            url: "/api/commons/system/getServerInfo",
            data: {
              sysIds: item.sysId,
            },
          }).then((res) => {
            if (res.code == 200) {
              let url =
                res.data[0].webSvrAddr +
                item.appLink
                  .replace("[token]", getToken())
                  .replace(
                    "[identityCode]",
                    storage.get("lg_ic") || Utils.getQueryVariable("lg_ic")
                  )
                  .replace(
                    "[IdentityCode]",
                    storage.get("lg_ic") || Utils.getQueryVariable("lg_ic")
                  );
              window.open(url, "_self");
            } else {
              dispatch({
                type: "SHOW_TOAST",
                data: "block",
              });
              // Toast.show({
              //   content:'请前往电脑端查看详情',
              //   position:'bottom',
              //  })
            }
          });
        }
      } else if (item.pcLinkType == 3 && item.appLink) {
        let url = item.appLink
          .replace("[token]", getToken())
          .replace(
            "[IdentityCode]",
            storage.get("lg_ic") || Utils.getQueryVariable("lg_ic")
          );
        window.open(url, "_self");
      } else {
        dispatch({
          type: "SHOW_TOAST",
          data: "block",
        });
        // Toast.show({
        //   content:'请前往电脑端查看详情',
        //   position:'bottom',
        //  })
      }
    } else {
      if (item.sysId === "241" && item.appLink) {
        //信箱只跳嵌入页面
        let jumpParam = item.appLink.split("?"),
          parsm = "";

        jumpParam[0] += `?env=weapp&schoolId=${userInfo.SchoolID}`;

        for (let i = 1; i < jumpParam.length; i++) {
          if (i === 1) {
            jumpParam[i] = "&" + jumpParam[i];
          } else if (i === 2) {
            jumpParam[i] = "?" + jumpParam[i];
          }
        }
        let urlStr = jumpParam
          .join("")
          .replace("[token]", Utils.getNowToken())
          .replace("[identityCode]", lg_ic);
        Taro.getSysWeb({ sysId: "241" }, "web", function (data) {
          let url = `${data}${urlStr}`;
          window.open(Proxy.transmitUrlToVisit(url), "_self");
        });
      } else if (item.sysId === "220" && item.appLink) {
        let url =
          window.baseUrl +
          item.appLink
            .replace("[token]", getToken())
            .replace(
              "[IdentityCode]",
              storage.get("lg_ic") || Utils.getQueryVariable("lg_ic")
            );
        url = useTransformUrl(url, { schoolId: SchoolID, env: "weapp" });
        window.open(Proxy.transmitUrlToVisit(url), "_self");
      } else {
        if (item?.appletsLink && item.pcLinkType == 1) {
          // 旧版小程序跳转
          if (item.appletsLink.indexOf("wxLogin") > -1) {
            let paramsArr = item.appletsLink.split("#");
            let appid = paramsArr[0];
            let path = paramsArr[1];

            for (let i = 2; i < paramsArr.length; i++) {
              //若传入的链接包含多个#
              path += "#" + paramsArr[i];
            }
            jumpWeapp(appid, path);
          } else {
            // let newUrl = useTransformUrl(item.appletsLink, { env: 'weapp', schoolId: userInfo.SchoolID })
            // console.log(newUrl,'@@@@',item.appletsLink)
            Taro.getSysWeb({ sysId: item.sysId }, "web", function (data) {
              let url =
                data +
                item.appletsLink
                  .replace("[token]", getToken())
                  .replace("[identityCode]", Utils.getQueryVariable("lg_ic"))
                  .replace("[IdentityCode]", Utils.getQueryVariable("lg_ic"));
              url = useTransformUrl(url, {
                env: "weapp",
                schoolId: userInfo.SchoolID,
              });
              window.open(Proxy.transmitUrlToVisit(url), "_self");
            });
          }
        } else {
          dispatch({
            type: "SHOW_TOAST",
            data: "block",
          });
        }
      }
    }
  };

  const getShowThisMsg = (item) => {
    //获取当前待办在此环境是否展示
    if (Utils.getSystemInfo() === "weapp") {
      //小程序环境
      switch (String(item.receiverType)) {
        case "0":
        case "3":
        case "5":
        case "6":
          return true;
        default:
          return false;
      }
    } else {
      switch (String(item.receiverType)) {
        case "0":
        case "2":
        case "4":
        case "6":
          return true;
        default:
          return false;
      }
    }
  };

  // 屏蔽消息
  const shieldMessage = (mes) => {
    const { UserID, UserType, SchoolID } = userInfo;
    HttpPut({
      url: "/api/setting/manage/batch/shield",
      data: {
        schoolId: SchoolID,
        userId: UserID,
        isPushList: [
          {
            templateId: mes.templateId,
            isPush: 0,
          },
        ],
      },
    }).then((result) => {
      if (result.code == 200) {
        setTimeout(() => {
          Taro.showToast({
            title: "屏蔽成功",
          });
        }, 500);
        getSysMes();
        window.getNewRemindCount &&
          typeof window.getNewRemindCount &&
          window.getNewRemindCount();
      }
    });
    setIsLongPress(false);
  };

  // 删除消息
  const delMessage = (mes) => {
    const { UserID, UserType, SchoolID } = userInfo;
    Taro.showModal({
      title: "提示",
      content: "是否删除选中消息",
      success: function (res) {
        if (res.confirm) {
          HttpDelete({
            url: "/api/system/manage/batch/delete",
            data: {
              schoolId: SchoolID,
              userId: UserID,
              sysMsgReceiverIds: [mes.sysMsgReceiverId],
            },
            load: true,
          }).then((result) => {
            if (result.code == 200) {
              setTimeout(() => {
                Taro.showToast({
                  title: "删除成功",
                });
              }, 500);
              getSysMes();
              window.getNewRemindCount &&
                typeof window.getNewRemindCount &&
                window.getNewRemindCount();
            }
            setIsLongPress(false);
          });
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  };

  // 获取系统消息
  const getSysMes = (n = 1) => {
    let { SchoolID, UserID, UserType } = userInfo;
    HttpGet({
      url: "/api/system/list/getPageList",
      data: {
        pageIndex: currentIndex,
        pageSize: 9999,
        schoolId: SchoolID,
        userId: UserID,
        userType: UserType,
        keyWord: keyword,
      },
      load: true,
    }).then((result) => {
      let mesList = result.data;

      if (Array.isArray(mesList) && mesList.length > 0) {
        let newList = mesList.filter((item) => getShowThisMsg(item));
        setTotal(newList.length);
        setTotalPage(Math.ceil(newList.length / 10));
        setSysMesList(newList);
      } else {
        setTotal(0);
        setTotalPage(0);
        setSysMesList([]);
      }
      setLoadVisible(false);
    });
  };

  // 执行清除系统消息
  const clearAllMes = () => {
    setIsOpened(true);
    const { UserID, UserType, SchoolID } = userInfo;
    HttpDelete({
      url: "/api/system/manage/delete/all",
      data: {
        schoolId: SchoolID,
        userId: UserID,
      },
    }).then((result) => {
      if (result.code == 200) {
        getSysMes();
        setTimeout(() => {
          Taro.showToast({
            title: "删除成功",
          });
        }, 500);
      }
    });
  };

  // 无限刷新
  const onPull = () => {
    if (totalPage > pullCount) {
      Taro.showLoading();
      setTimeout(() => {
        Taro.hideLoading();
      }, 2000);
      setPullCount(pullCount + 1);
      getSysMes(pullCount + 1);
    } else {
      Taro.showToast({
        title: "到底啦",
        icon: "none",
      });
    }
  };

  // 下拉刷新
  const onDown = () => {
    getSysMes();
    setTimeout(() => {
      Taro.showToast({
        title: "刷新成功",
      });
    }, 500);
  };

  useEffect(() => {
    getSysMes();
  }, [currentIndex, keyword]);

  return (
    <>
      <View className="sys_container">
        <View className="sys_header">
          <View className="font-header">
            共<Text className="num">{total}</Text>条消息
          </View>
          <View className="right_option">
            {isSearch ? (
              <View className="my_ipt animate__animated animate__slideInRight animate__faster">
                <LgSearch
                  value={keyword}
                  onConfirm={(value: string) => setKeyword(value.trim())}
                  placeholder="请输入..."
                  onInput={searchHandle}
                />
              </View>
            ) : (
              <View
                className="my_search_icon"
                onClick={() => setIsSearch(true)}
              ></View>
            )}
            <View onClick={clearAll} className="clear_btn"></View>
          </View>
        </View>
        <LgRefreshPage
          className="index"
          onPull={onPull}
          onDown={onDown}
          downText={["下拉刷新", "释放刷新"]}
          pullText={["上拉加载更多", "释放加载更多"]}
        >
          {sysMesList.length > 0 ? (
            sysMesList.map((item, index) => {
              // 接收者类型为app
              if (getShowThisMsg(item)) {
                return (
                  <SwipeAction rightActions={computeSwipe(item)}>
                    <View>
                      <Card
                        type="C"
                        key={index}
                        content={item.msgPushContent}
                        time={item.msgPushTime.substring(0, 16)}
                        sourceName={item.msgSourceName}
                        status={item.status}
                        toLink={() => {
                          isLongPress ? setIsLongPress(false) : toLink(item);
                        }}
                        id={item.sysMsgId}
                        pressId={pressId}
                        isLongPress={isLongPress}
                        shieldMessage={() => {
                          shieldMessage(item);
                        }}
                        delMessage={() => {
                          delMessage(item);
                        }}
                      />
                    </View>
                  </SwipeAction>
                );
              }
            })
          ) : loadVisible ? (
            ""
          ) : (
            <Empty type="B" text="系统提醒"/>
          )}
        </LgRefreshPage>
      </View>
    </>
  );
}

const mainProps = ({ commonData }) => {
  return {
    userInfo: commonData.userInfo,
    baseUrl: commonData.baseUrl,
    lg_ic: commonData.lg_ic,
  };
};

export default connect(mainProps)(App);
